//
//  PageIterator.m
//  SimulacraDB
//
//  Created by Andre Cohen on 8/11/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "PageIterator.h"


@implementation PageIterator

- (id)initWithRecord:(Record *)record page:(Paging *)handler {
	[super init];
	prototype = record;
	paging = handler;
	location = 0;
	page = 0;
	return self;
}

- (Record *)first {
	location = 0;
	page = 0;
	
	Record *r = [self recordForPage:page offset:location];
	return [paging getRecordAt:r];
}

- (Record *)next {
	while(true){
		if(location>=[paging blocksPerPage]){
			location=0;
			page++;
		}
		if(page==[paging pageCount])
			return nil;
		if(![paging getBlockAtPage:page offset:location]){
			location++;
		}else{	
			Record *r = [self recordForPage:page offset:location];
			
			r = [paging getRecordAt:r];
			if(r==nil)
				return nil;
			
			location=location+ceil([r size]/([paging blockSize] * 1.0));

			return r;
		}
	}
	return nil;
}

- (Record *)recordForPage:(int)p offset:(int)off {
	Record *r = [prototype clone];
	UInt64 rid = p;
	rid = (rid<<32) + off;
	[[r wrapper] setRid:[RID createWithValue:rid]];
	return r;
}

@end


